<?php
/*
 ###########################################################################
 #
 #        Zhejiang Job Educational Technology Company
 #
 ###########################################################################
 #
 #  Filename: userbc_controller.php
 #
 #  Description:
 #
 #
 ###########################################################################
 #
 #    R E V I S I O N   L O G
 #
 #    Date       Name            Description
 #    --------   --------------- -------------------------------
 #    2011/7/14   Gu wen         Created.
 #
 ###########################################################################
 */


/**
 * Controller_Admin 控制器
 */
class Controller_Admin extends Controller_Abstract
{
	function __construct($app){
		parent::__construct($app);
		
	}
	function actionIndex()
	{
        // 为 $this->_view 指定的值将会传递数据到视图中
		# $this->_view['text'] = 'Hello!';
		//dump($_SESSION);
		//print_r(Admin::get_all_perms());
		$where="[isdelete]=0";
		$user = $this->_app->currentUser();
		$page = (int)$this->_context->page;
		if ($page==0) $page++;
		//echo $page;exit;
		$limit = $this->_context->limit ? $this->_context->limit : 15;
		$q = Admin::find('[isdelete]=?',0)->limitPage($page, $limit);
		$this->_view['pager'] = $q->getPagination();
		$this->_view['list'] = $q->getAll();
		$this->_view['start'] = ($page-1)*$limit;
		$this->_view['subject'] = "帐号管理";
		$user = $this->_app->currentUser();
		$this->_view['all_group'] = Group::find('isdelete=0')->getAll()->toHashMap('id','groupname');
	}
	
	function actionCreate(){
		// 构造表单对象
		$form = new Form_Admin('');
		$user = $this->_app->currentUser();
		if ($this->_context->isPOST() && $form->validate($_POST))
		{
			// 创建 admin 对象并保存
			$data = $form->values();
			if($data['groupid']){
				$group = Group::find()->getById($data['groupid']);
				$data['perms'] = $group->perms;
				if($data['groupid'] != 3){
					$data['school_id'] = 0;
				}
			}
			$admin = new Admin($data);				
				// 	创建成功后，重定向浏览器
				 //$this->_redirect(url(''));
			$args = Admin::find('username=?&&isdelete=0',$admin->username)->getAll();
			$num = count($args);
			$admin->update_id = $user['id'];
			$admin->update_date = time();
			if($form['newpassword']==""){
				$form['newpassword']->invalidate("确认密码不为空");
			}
			if ($num>0) {
				$form['username']->invalidate("{$admin->username}已经存在");
			} else{
				$admin->save();
				// 	创建成功后，重定向浏览器
				return $this->_redirect(url(''));
			}			
		}
		// 将表单对象传递给视图
		$this->_view['form'] = $form;
		$this->_view['subject'] = "系统帐号";
		$this->_view['edit']=0;
	}
	
	
	function actionEdit(){
		$id = $this->_context->id;
		//$admin = Admin::find('id = ?', $id)->query();
	 	$admin = Admin::find()->getById($id);	 	
	 	
	 	$user = $this->_app->currentUser();
	 	
	 	
		// 构造表单对象
		$form = new Form_Admin('');
		// 修改表单标题
		$this->_view['subject'] = "帐号管理";
	    $form->_subject = "修改帐号";
	    $form->edit=1;
		if ($this->_context->isPOST())
		{
			// changeProps() 方法可以批量修改对象的属性，但不会修改只读属性的值
			if($form->validate($_POST)){
				$data = $form->values();
				unset($data['newpassword']);
				if($form['password']->value==""){
					unset($data['password']);
				}
				if($data['groupid'] != 3){
					$data['school_id'] = 0;
				}
				$admin->changeProps($data);
			// 保存并重定向浏览器
				$args = Admin::find('username=?&&isdelete=0?&&id!=?',$admin->username,0,$id)->getCount();
				if ($args>0) {
					$form['username']->invalidate("{$admin->username}已经存在了");
				}else{
					$admin->save();
					// 	创建成功后，重定向浏览器
					return $this->_redirect(url('admin'));
				}
			}else{
				// 如果不是 POST 提交，则把对象值导入表单
				/*
				if(isset($form['password'])){
				$form['password']->value="";
				}
				*/
			}
				
		}
		elseif (!$this->_context->isPOST())
		{
			// 如果不是 POST 提交，则把对象值导入表单
			$form->import($admin);
			$form['password']->value="";
        }
        //dump($form);
		$this->_view['form'] = $form;
		$this->_view['edit']=1;
		// 重用 create 动作的视图
		$this->_viewname = 'create';
    }

	function actionDelete(){
		$admin = Admin::find('id = ?', $this->_context->id)->getOne();
		$stu_id = $admin->username;
	 	$admin->isdelete = 1;
	 	$admin->username = time()."_d_".$admin->username;
		$admin->save();
		return $this->_redirect(url('admin'));
	}
    /**
     * 学历教育管理系统登录口
     */
    function actionLogin()
    {
        $form = new Form_UserLogin(url('admin/login'));
        $error = array(
        			'username' 	=> '',
        			'password' 	=> '',
        			'message'	=> '',
        			);
        $user_type = 0;
        if ($this->_context->isPOST() && $form->validate($_POST))
        {//dump($_POST);
            try
            {
                $user_type = $_POST['user_type'];
                switch($user_type){
                	case 1://管理员
		            	// 使用 acluser 插件的 validateLogin() 方法验证登录并取得有效的 user 对象
		                $user = Admin::meta()->validateLogin($form['username']->value, $form['password']->value);                
		                if($user['isdelete']==1){
		                    $error['username'] = "您的帐号已被删除！";
		                }else if($user['valid']==0){
		                    $error['username'] = "您的帐号处于无效状态！";
		                }else{
		                    // 将登录用户的信息存入 SESSION，以便应用程序记住用户的登录状态
							$aclData = $user->aclData();
							$aclData['news_op'] = $user['news_op']; //新闻权限字段，判断用户有哪些类型可以操作
		                    //dump($aclData);
		                    $this->_app->changeCurrentUser($aclData, 'MEMBER');
		                    // 登录成功后，重定向浏览器
                            return $this->_redirect( url('default/main'));
                            //return $this->_redirect($this->actionCjgate());
		                } 
	                	break;
                	case 3://学生
                		// 使用 acluser 插件的 validateLogin() 方法验证登录并取得有效的 user 对象
		                $user = User::meta()->validateLogin($form['username']->value, $form['password']->value);                
		                if(0 && !$user->validCheck()){
		                    $error['username'] = "对不起，该学生账号已经过期！";
		                }else{
							if($user->sims_lev == 0){
								// 将登录用户的信息存入 SESSION，以便应用程序记住用户的登录状态
								$aclData = $user->aclData();
								$aclData['id'] = $user->userid;
								//$aclData['school_id'] = $user['school_id'];
								//print_r($aclData);
								$this->_app->changeCurrentUser($aclData, 'MEMBER');
								// 登录成功后，重定向浏览器
								return $this->_redirect( url('default/index'));
								//return $this->_redirect($this->actionCjgate());
							}else{
								$error['username'] = "对不起，该学生账号不存在！";
							}
		                } 
                		break;
                }
            }
            catch (AclUser_UsernameNotFoundException $ex)
            {
                $error['message'] = "您输入的登录帐号 {$form['username']->value} 不存在";
            }
            catch (AclUser_WrongPasswordException $ex)
            {
                $error['password'] = "您输入的密码不正确";
            }
        }
        if(isset($_GET['user_type'])){
        	$user_type = $_GET['user_type'];
        }
		$this->_view['error'] = $error;
        $this->_view['form'] = $form;
        $this->_view['user_type'] = $user_type;//dump($user);
        //$this->_viewname = 'register';
    }
    /**
     * 注销
     */
    function actionLogout()
    {
       	$user = $this->_app->currentUser();
		$logout_url = url('default/index');
        $this->_app->cleanCurrentUser();
        $_SESSION = array();
        //$logout_url =  '/admin/login';//QContext::instance()->baseDir()."lms/doceboLms/index.php?modname=login&op=logout&act=logout";
        return $this->_redirect($logout_url);
    }

    function actionAuth() {
        $id = $this->_context->id;
        $alert = '';
        $admin = Admin::find()->getById($id);
        $myData = $admin->toArray();
	 	$myData['perms'] = json_decode($myData['perms'],true);
	 	$this->_view['myData'] = $myData;
       	$user = $this->_app->currentUser();
       
        
        if ($this->_context->isPOST()) {
            $perms = '';
			if(isset($_POST['perms'])){
				$perms = json_encode($_POST['perms']);
			}
			$user = $this->_app->currentUser();
			$form_value = array(
							'perms'			=> $perms,
							'update_id'		=> $user['id'],
							'update_date'	=> time(),
							);
			//print_r($form_value);
			$admin -> changeProps($form_value);
			$admin -> save();
			$alert = "<script language='javascript'>alert('修改成功！');window.open('".url('admin')."','_self');</script>";
        }
        $this->_view['all_perms'] = Admin::get_all_perms();
        $this->_view['subject'] = '修改权限';
        $this->_view['alert'] = $alert;
    }
    
    function actionProfile(){
    	$user = $this->_app->currentUser();
    	$id = $user['id'];
	 	$admin = Admin::find()->getById($id);
		// 构造表单对象
		$form = new Form_Profile('');
		// 修改表单标题
		$this->_view['subject'] = "帐号管理";
		$form->_subject = "我的帐号";
		//自己不能修改账号名称
		$this->_view['readonly'] = 1;
	    //$form->edit=1;
		if ($this->_context->isPOST())
		{
			// changeProps() 方法可以批量修改对象的属性，但不会修改只读属性的值
			if($form->validate($_POST)){
				// 保存并重定向浏览器
					$args = Admin::find('username=?&&isdelete=0?&&id!=?',$form['username']->value,0,$id)->getCount();
				if ($args>0) {
					$form['username']->invalidate("{$admin->username}已经存在了");
				}else{
					$data = $form->values();
					unset($data['isprofile']);
					if($form['password']->value==""){
						unset($data['password']);
					}
					unset($data['newpassword']);
					//dump($data);die;
					$admin->changeProps($data);
					$admin->save();
					// 	创建成功后，重定向浏览器
					$this->_view['suc']="suc";
				}
			}else{
				// 如果不是 POST 提交，则把对象值导入表单
				$form->import($admin);
				if(isset($form['password'])){
				$form['password']->value="";
				}
			}
		}
		elseif (!$this->_context->isPOST())
		{
			// 如果不是 POST 提交，则把对象值导入表单
			$form->import($admin);
			$form['password']->value="";
			$user = $this->_app->currentUser();
			$id = $user['id'];
			$index = Admin::find('isdelete=0?&&id=?',0,$id)->getOne();
			$form['username']->value=$index['username'];
			$form['name']->value=$index['name'];
		}
		$this->_view['form'] = $form;
		$this->_view['edit']=2;
		// 重用 create 动作的视图
		$this->_viewname = 'create';
    }

    function actionCjgate(){//跳转学习系统
        $user = $this->_app->currentUser();//获取登录用户
        $id = $user['id'];
		if ($user['user_type'] == 1) {
        	$admin = Admin::find("id=?",$id)->getOne();
            $url = QContext::instance()->baseDir()."lms/index.php?username=".$admin['username']."&password=".$admin['password'];
        } else {
            $stu = Users::find("userid=?",$id)->getOne();
            $url = QContext::instance()->baseDir()."lms/index.php?username=".$stu['userid']."&password=".$stu['pass'];
        }
        return $url;
	}
		//新闻权限
	function actionOpnews() {
        $id = $this->_context->id;
        $alert = '';
        $admin = Admin::find()->getById($id);
        $myData = $admin->toArray();
	 	//$myData['perms'] = json_decode($myData['perms'],true);
	 	$this->_view['myData'] = $myData;
       	$user = $this->_app->currentUser();
       
        
        if ($this->_context->isPOST()) {
			$news_op = '';
			//print_r($_POST['news_op']);
			//echo '<br />';
				
			if(isset($_POST['news_op'])){
				$news_op = implode(',',$_POST['news_op']);
			}
			//echo $news_op;
			$user = $this->_app->currentUser();
			$form_value = array(
							'news_op'		=> $news_op,
							'update_id'		=> $user['id'],
							'update_date'	=> time(),
							);
			//print_r($form_value);
			$admin -> changeProps($form_value);
			$admin -> save();
			$alert = "<script language='javascript'>alert('修改成功！');window.open('".url('admin')."','_self');</script>";
        }
        //$this->_view['all_perms'] = Admin::get_all_perms();
        $this->_view['subject'] = '修改新闻权限';
		$this->_view['alert'] = $alert;
		//列出所有新闻类型
		$newstype = new Newstype();
       	$list = $newstype->get_select_list();
       	unset($list[0]);
		$this->_view['list'] = $list;
    }
}


